//
//  StatusCellPictureView.swift
//  sinaDemo
//
//  Created by mac on 15/12/19.
//  Copyright © 2015年 zhouxubin. All rights reserved.
//

import UIKit
import SnapKit

let pictureMargin: CGFloat = 5
let pictureCell = "picture_cell"

class StatusCellPictureView: UICollectionView {
    // MARK:定义外部模型属性
    
    var imageURLs: [NSURL]? {
        didSet {
            //修改配图视图的大小
            let pSize = caclePictureViewSize()
            //更新配图视图的大小
            self.snp_updateConstraints { (make) -> Void in
                make.size.equalTo(pSize)
            }
            
            
            //修改测试的文案
            testLabel.text = "\(imageURLs?.count ?? 0)"
            reloadData()
        }
    }
    
    // MARK:重写构造方法
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        //实例化一个 流水布局
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.minimumInteritemSpacing = pictureMargin
        flowLayout.minimumLineSpacing = pictureMargin
        super.init(frame: frame, collectionViewLayout: flowLayout)
//        backgroundColor = UIColor(white: 0.91, alpha: 1)
        backgroundColor = UIColor.whiteColor()
        self.dataSource = self
        self.delegate = self
        // 设置点击顶部不能回到顶部
        self.scrollsToTop = false
        self.registerClass(statusPictureCell.self, forCellWithReuseIdentifier: pictureCell)
        //设置视图
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /*
    单图会按照图片等比例显示
    多图的图片大小固定
    多图如果是4张，会按照 2 * 2 显示
    多图其他数量，按照 3 * 3 九宫格显示
    */
    
    //计算配图视图的大小
    private func caclePictureViewSize() -> CGSize {
        //计算配图的大小
        //1.获取配图的数量
        let imageCount = imageURLs?.count ?? 0
        //获取配图视图的最大宽度
        let maxWidth = screenBoundsWidth - 2 * statusCellMargin
        let itemWidth = (maxWidth - 2 * pictureMargin) / 3
        
        // 取出layout
        let flowlayout = self.collectionViewLayout as! UICollectionViewFlowLayout
        flowlayout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        
        //没有图片
        if imageCount == 0 {
            return CGSizeZero
        }
        //单张图片
        if imageCount == 1 {
            //TODO: 单图会按照图片等比例显示
            //先给定固定尺寸
            let imageSize = CGSize(width: 180, height: 120)
            flowlayout.itemSize = imageSize
            return imageSize
        }
        
        if imageCount == 4 {
            //多图如果是4张，会按照 2 * 2 显示
            let w = itemWidth * 2 + pictureMargin
            return CGSize(width: w, height: w)
        }
        
        //如果程序走到这里 就是其他的多张图片
        //1. 确定有多少行
        /*
        1,2,3  -> 1
        4,5,6  -> 2
        7,8,9  -> 3
        先 整体 + 1  -> 修正 分子 -1
        */
        let row = CGFloat((imageCount - 1) / 3 + 1)
        
        return CGSize(width: maxWidth, height: row * itemWidth + (row - 1) * statusCellMargin )
    }
    
    // MARK:设置页面 和 布局
    private func setupUI() {
        self.addSubview(testLabel)
        testLabel.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(self.snp_center)
        }
    }
    
    
    // MARK:懒加载所有的子视图
    private lazy var testLabel: UILabel = UILabel(title: "", color: UIColor.redColor(), textFont: 30)
}

extension StatusCellPictureView: UICollectionViewDataSource, UICollectionViewDelegate {
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imageURLs?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(pictureCell, forIndexPath: indexPath) as! statusPictureCell
        // 取出url数组中的url
        let url = imageURLs![indexPath.row]
        cell.imageUrl = url
        cell.backgroundColor = UIColor.randomColor()
        
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        let browser = SDPhotoBrowser()
        browser.sourceImagesContainerView = self
        browser.imageCount = imageURLs?.count ?? 0
        browser.currentImageIndex = indexPath.item
        browser.delegate = self
        browser.show()
        /*
        创建SDPhotoBrowser实例
        
        SDPhotoBrowser *browser = [[SDPhotoBrowser alloc] init];
        
        browser.sourceImagesContainerView = 原图的父控件;
        
        browser.imageCount = 原图的数量;
        
        browser.currentImageIndex = 当前需要展示图片的index;
        
        browser.delegate = 代理;
        
        [browser show]; // 展示图片浏览器
        */
    }
}

extension StatusCellPictureView: SDPhotoBrowserDelegate {
    // 高质量的占位图片
    func photoBrowser(browser: SDPhotoBrowser!, highQualityImageURLForIndex index: Int) -> NSURL! {
        if let placeholderString = imageURLs?[index].absoluteString {
            // 将低质量的url转换成高质量的url
            let highQualityImageUrl = placeholderString.stringByReplacingOccurrencesOfString("thumbnail", withString: "large")
            return NSURL(string: highQualityImageUrl)
        }
        return nil
    }
    
    // 占位图片
    func photoBrowser(browser: SDPhotoBrowser!, placeholderImageForIndex index: Int) -> UIImage! {
        let indexPath = NSIndexPath(forItem: index, inSection: 0)
        if let cell = self.cellForItemAtIndexPath(indexPath) as? statusPictureCell {
            return cell.imageV.image
        }
        return nil
    }
}

class statusPictureCell: UICollectionViewCell {
    
    // 定义外部属性,设置url的时候就设置图片
    var imageUrl: NSURL? {
        didSet {
            imageV.sd_setImageWithURL(imageUrl)
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUpSubViews()
    }
    
    private func setUpSubViews() {
        // 初始化子控件
        contentView.addSubview(imageV)
        
        // 添加约束
        imageV.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self)
        }
    }
    
    // MARK: 懒加载子控件
    private lazy var imageV: UIImageView = {
        let cellImageView = UIImageView()
        cellImageView.userInteractionEnabled = true
        // 设置图片的拉伸格式
        cellImageView.contentMode = UIViewContentMode.ScaleAspectFill
        cellImageView.clipsToBounds = true
        return cellImageView
    }()
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

